package com.shopoo.oauth.wechat.service;

import java.util.List;

import javax.annotation.Resource;

import com.shopoo.exception.Assert;
import com.shopoo.oauth.domain.entity.Role;
import com.shopoo.oauth.domain.repository.RoleRepository;
import com.shopoo.oauth.domain.valueobject.UserAuth;
import com.shopoo.oauth.wechat.utils.JwtUtil;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Description 用户细节服务实现
 *
 * @Param 
 * @Return 
 * @Date 1:57 下午 2020/10/29
 * @Author <a href="mailto:android_li@sina.cn">Joe</a>
 */
@Service
public class CustomUserDetailsService {

    @Value("${wechat.oauth2.password:s3k21sfSEdsfsfFSofwsoq}")
    private String wechatOauth2Password;

    @Resource
    private RoleRepository roleRepository;

    /**
     * @Description: 该token为微信授权获取到的用户加密信息
     * @Author: limy66
     * @Date:   2021/1/27 18:25
     * @Param:  [token]
     * @Return: com.szmengran.oauth.infrastructure.db.entity.OauthUser
     */
    public UserAuth loadUserByToken(String token) {
        Assert.notNull(token, "token不能为空！");
        String userId = JwtUtil.parseToken(token, wechatOauth2Password);
        Assert.notNull(userId, "微信授权生成的token无效！");
        // 判断成功后返回用户细节
        UserAuth user = new UserAuth();
        user.setUserId(userId);
        user.setUsername(userId);
        List<Role> roles = roleRepository.findByUserId(user.getUserId());
        user.setAuthorities(roles);
        return user;
    }

}
